//
//  WmcCloudMineVM.swift
//  YPWatermarkCamera
//
//  Created by 赵新 on 2022/3/31.
//

import UIKit
import RxRelay
import YPNetwork
import Foundation
import JXPhotoBrowser

extension WmcCloudMineVM {
    class CellModel {
        // Lifecycle

        init(title: String,
             style: Style,
             rowHeight: CGFloat = 57,
             actionType: ActionType) {
            self.title = title
            self.style = style
            self.rowHeight = rowHeight
            self.actionType = actionType
        }

        // Internal

        enum Style {
            case none
            case cover(_ name: String)
            case text(_ text: String, color: UIColor, font: UIFont)
            case `switch`(_ isOn: Bool)
            /// 只有按钮操作类型 例如（退出登录，注销账号）
            case onyAction(_ textColor: UIColor)
            /// 头像类型
            case userAvatar(_ namex: String, img: String)
        }

        enum ActionType {
            /// 头像
            case avatar
            /// 编辑名字
            case editName
            /// 绑定手机号
            case bindMobile
            /// 同步相册
            case synchronize
            /// 意见反馈
            case feedback
            /// 推荐好友
            case recommend
            /// 注销账号
            case cancelAccount
            /// 退出登录
            case logout
        }

        /// 标题
        var title: String
        /// 样式
        var style: Style
        /// 高度
        var rowHeight: CGFloat

        var actionType: ActionType
    }

    /// 模式
    enum Mode {
        /// 我的
        case mine
        /// 设置
        case setting

        struct Info {
            var title: String
        }

        /// 信息
        var info: Info {
            switch self {
            case .mine: return .init(title: "我的")
            case .setting: return .init(title: "设置")
            }
        }
    }
}

// MARK: - [WmcCloudMineVM]

class WmcCloudMineVM: WmcBaseVM {
    // Internal

    /// 显示模式
    /// 我的和设置，展示的数据结构不同
    var showMode: Mode = .mine

    /// 数据列表
    let dataListRelay: BehaviorRelay<[[CellModel]]> = .init(value: [])

    var updatedAvatar: String?

    /// 加载数据
    func loadList() {
        var list: [[CellModel]] = []
        switch showMode {
        case .mine:
            /// 组1
            let group_0: [CellModel] = [
                avatarModel,
                editNameModel,
                bindPhoneModel,
            ]
            list.append(group_0)

            /// 组2
            let group_1: [CellModel] = [
                .init(title: "意见反馈", style: .none, actionType: .feedback),
                .init(title: "推荐给好友", style: .none, actionType: .recommend),
            ]
            list.append(group_1)

            /// 组3
            let group_2: [CellModel] = [
                .init(title: "退出登录", style: .onyAction(UIColor.wmc_blue_5290FD), actionType: .logout),
                .init(title: "注销账号", style: .onyAction(UIColor.wmc_red_F54A45), actionType: .cancelAccount),
            ]
            list.append(group_2)

        case .setting: break
        }

        dataListRelay.accept(list)
    }

    func queryUserInfo(completion: (() -> Void)? = nil) {
        WmcUserCenterAPI.fetchUserInfo().subscribe(onNext: { [weak self] value in
            guard let weakSelf = self else { return }
            let name = value.name
            let phone = value.phone
            let hidePhone = weakSelf.hidePhoneNumber(number: phone)

            var avatar: String = ""

            if let ava = weakSelf.updatedAvatar {
                avatar = ava
            } else {
                avatar = value.avatar
            }

            // self.avatarModel.style = .cover(name)
            weakSelf.avatarModel.style = .userAvatar(name, img: avatar)
            weakSelf.editNameModel.style = .text(name, color: .wmc_grayH2_323233, font: 17.wmc_font)
            weakSelf.bindPhoneModel.style = .text(hidePhone, color: .wmc_grayH2_323233, font: 17.wmc_font)
            completion?()
        }).disposed(by: rx.disposeBag)
    }

    /// 部分显示手机号
    /// - Parameter number: 手机号
    /// - Returns: description
    func hidePhoneNumber(number: String) -> String {
        if number.count < 5 {
            var str = ""
            for _ in 0 ..< number.count {
                str += "*"
            }
            return str
        } else {
            let start = number.index(number.startIndex, offsetBy: (number.count - 5) / 2)
            let end = number.index(number.startIndex, offsetBy: (number.count - 5) / 2 + 4)
            let range = Range(uncheckedBounds: (lower: start, upper: end))
            return number.replacingCharacters(in: range, with: "****")
        }
    }

    /// Private
    private lazy var avatarModel: CellModel = {
        //  let model = CellModel(title: "头像", style: .cover(""), rowHeight: 80, actionType: .avatar)、
        let model = CellModel(title: "头像", style: .userAvatar("", img: ""), rowHeight: 80, actionType: .avatar)
        return model
    }()

    private lazy var editNameModel: CellModel = {
        let model = CellModel(title: "修改名字", style: .text("", color: .wmc_grayH2_323233, font: 17.wmc_font), actionType: .editName)
        return model
    }()

    private lazy var bindPhoneModel: CellModel = {
        let model = CellModel(title: "换绑手机号", style: .text("", color: .wmc_grayH2_323233, font: 17.wmc_font), actionType: .bindMobile)
        return model
    }()
}

extension WmcCloudMineVM {
    /// 更新头像
    /// - Parameters:
    ///   - imgUrl: imgUrl description
    ///   - succeedBlock: succeedBlock description
    /// - Returns: description
    func updateUserAvatar(imgUrl: String, succeedBlock: (() -> Void)?) {
        WmcHudManager.loading()
        WmcMediaUserCenterAPI.updateAvatar(imageUrl: imgUrl).subscribe { res in
            WmcHudManager.dismiss()
            guard let succeedBlock = succeedBlock else {
                return
            }
            succeedBlock()
        } onError: { error in
            WmcHudManager.toast(error)
        }.disposed(by: rx.disposeBag)
    }

    /// 上传头像
    func uploadUserAvatar(_ image: UIImage,
                          successBlock: @escaping YPBlock.OneParam<String>,
                          failureBlock: YPBlock.Empty? = nil) {
        guard let imageData = image.yp.jpegData else { return }
        var params: WmcUploadFileModel = .init()
        params.entryId = 555595
        params.type = 0
        params.format = "png"

        WmcUploadManager.uploadFile(data: imageData, params: params, progress: nil) { value in
            successBlock(value.accessUrl)
        } failure: { error in
            failureBlock?()
            WmcHudManager.toast(error)
        }
    }
}
